package me.numark;

import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.model.Feed;
import me.numark.utils.Constants;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;

/**
 * Created by tian on 14/11/13:上午8:49.
 */
public class ShareActivity extends AuthenticatorActivity
        implements View.OnClickListener, IWeiboHandler.Response {

    @InjectView(R.id.background)
    FrameLayout content;

    @InjectView(R.id.share_weibo)
    TextView shareWeibo;

    @InjectView(R.id.share_wechat)
    TextView shareWeChat;

    @InjectView(R.id.share_timeline)
    TextView shareTimeline;

    @InjectView(R.id.share_qq)
    TextView shareQQ;

    @InjectView(R.id.cancel)
    TextView cancel;

    @InjectView(R.id.share_layout)
    View shareLayout;

    private Feed mFeed;

    private IWeiboShareAPI mWeiboApi;

    private String mFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        ButterKnife.inject(this);
        cancel.setOnClickListener(this);
        content.setOnClickListener(this);
        shareWeibo.setOnClickListener(this);
        shareQQ.setOnClickListener(this);
        shareWeChat.setOnClickListener(this);
        shareTimeline.setOnClickListener(this);
        mFeed = Feed.fromString(getIntent().getStringExtra(Constants.FEED_EXTRA));
        mFile = getIntent().getStringExtra(Constants.PICTURE_EXTRA);
        mWechatApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_KEY);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_in_from_bottom);
        shareLayout.startAnimation(animation);
        AlphaAnimation animation1 = new AlphaAnimation(0.0f, 1.0f);
        animation1.setDuration(200);
        animation1.setFillAfter(true);
        content.startAnimation(animation1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.background:
                finish();
                break;
            case R.id.share_weibo:
                shareWeibo();
                break;
            case R.id.share_timeline:
                shareWeChat(true);
                break;
            case R.id.share_wechat:
                shareWeChat(false);
                break;
            case R.id.share_qq:
                shareQQ();
                break;
            default:
                break;
        }
    }

    private void shareQQ() {
        Bundle b = new Bundle();
        b.putString(QQShare.SHARE_TO_QQ_TITLE, mFeed.news.title);
        if (!TextUtils.isEmpty(mFeed.news.subtitle)) {
            String s = mFeed.news.subtitle;
            if (s.length() > 40) {
                s = mFeed.news.subtitle.substring(0, 40);
            }
            b.putString(QQShare.SHARE_TO_QQ_SUMMARY, s);
        }
        if (!TextUtils.isEmpty(mFeed.news.face_img)) {
            b.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, mFeed.news.face_img);
        }
        if (!TextUtils.isEmpty(mFeed.news.url)) {
            b.putString(QQShare.SHARE_TO_QQ_TARGET_URL, mFeed.news.url);
        }
        b.putString(QQShare.SHARE_TO_QQ_SITE, "http://www.huxiu.com");
        b.putString(QQShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        b.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        b.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        mTencent.shareToQQ(this, b, this);
    }
    @Override
    public void finish() {
        content.setBackgroundColor(getResources().getColor(android.R.color.transparent));
        super.finish();
        overridePendingTransition(R.anim.push_out_to_bottom, R.anim.push_out_to_bottom);
    }

    private void initWeiBo() {
        WeiboAuth weiboAuth = new WeiboAuth(this, Constants.SinaAppKey,
                Constants.SinaAppRedirectURI, Constants.SinaScope);
        mSsoHandler = new SsoHandler(this, weiboAuth);
        mSsoHandler.authorize(this);
    }

    private void shareWeibo() {
        if (Settings.readWeiboAccessToken() == null) {
            initWeiBo();
        } else {
            mWeiboApi = WeiboShareSDK.createWeiboAPI(this, Constants.SinaAppKey);
            if (mWeiboApi.isWeiboAppSupportAPI()) {
                int supportApi = mWeiboApi.getWeiboAppSupportAPI();
                if (supportApi >= 10351 /*ApiUtils.BUILD_INT_VER_2_2*/) {
                    shareMultipleWeiboMessage();
                } else {
                    shareSingleWeiboMessage();
                }
            }
        }
    }

    private void shareMultipleWeiboMessage() {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
//        TextObject textObject = new TextObject();
//        textObject.text = mFeed.news.title;
//        ImageObject imageObject = new ImageObject();
//        imageObject.imagePath = mFile;
        WebpageObject webpageObject = new WebpageObject();
        webpageObject.identify = Utility.generateGUID();
        webpageObject.title = mFeed.news.title;
        webpageObject.setThumbImage(BitmapFactory.decodeFile(mFile));
        weiboMessage.mediaObject = webpageObject;
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        mWeiboApi.sendRequest(request);
    }

    private void shareSingleWeiboMessage() {
        WeiboMessage weiboMessage = new WeiboMessage();
        ImageObject imageObject = new ImageObject();
        imageObject.imagePath = mFile;
        TextObject textObject = new TextObject();
        textObject.text = mFeed.news.url;
        weiboMessage.mediaObject = textObject;
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;
        mWeiboApi.sendRequest(request);
    }

    private IWXAPI mWechatApi;

    private void shareWeChat(boolean isTimeline) {
        if (!mWechatApi.isWXAppInstalled()) {
            Toast.makeText(this, R.string.wechat_not_installed, Toast.LENGTH_SHORT)
                    .show();
            return;
        } else if (!mWechatApi.isWXAppSupportAPI()) {
            Toast.makeText(this, R.string.wechat_not_supported, Toast.LENGTH_SHORT)
                    .show();
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = mFeed.news.url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = mFeed.news.title;
        msg.setThumbImage(BitmapFactory.decodeFile(mFile));
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage" + +System.currentTimeMillis();
        req.message = msg;
        req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        boolean b = mWechatApi.sendReq(req);
        LogUtils.d("send wx result: " + b);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mWeiboApi.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibo_share_success, Toast.LENGTH_LONG)
                        .show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibo_share_cancel, Toast.LENGTH_LONG)
                        .show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this,
                        getString(R.string.weibo_share_failed) + ": "
                                + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }

    }
}
